package nix.bs.dao;

import java.sql.SQLException;
import java.util.List;

import nix.bs.domain.Category;
import nix.jdbc.TxQueryRunner;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

public class CategoryDao {

	private QueryRunner qr = new TxQueryRunner();

	public List<Category> findAll() {
		try {
			return qr.query("select * from tb_category",
					new BeanListHandler<Category>(Category.class));
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void add(Category category) {
		try {
			qr.update("insert into tb_category (cid, cname) values (?, ?)",
					category.getCid(), category.getCname());
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void delete(String cid) {
		try {
			qr.update("delete from tb_category where cid = ?", cid);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public Category load(String cid) {
		try {
			return qr.query("select * from tb_category where cid = ?",
					new BeanHandler<Category>(Category.class), cid);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void edit(Category category) {
		try {
			qr.update("update tb_category set cname = ? where cid = ?",
					category.getCname(), category.getCid());
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

}
